/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SqlServer.Management.Smo;
using System.Web.UI.HtmlControls;
using System.Globalization;

/// <summary>
/// Clasa care contine diverse functii statice.
/// </summary>
public class Tools
{
	public static string LOG_GENERAL = "";
	public static string LOG_INFO = "_info";
    public static string userHipo = null;
    public static string StaffID = null;
    public static string userHipoSession = null;
    public static string userLogin = null;

	public Tools()
	{
	}

	/// <summary>
	/// Returneaza System.DBNull.Value in loc de null sau sirul vid.
	/// </summary>
	/// <param name="o">Valoarea de intrare.</param>
	/// <returns>Valoarea de iesire.</returns>
	public static object GetSQLValue(object o)
	{
		if ((o == null) || (o is System.DBNull) || ((o is string) && ((string)o == "")))
			return System.DBNull.Value;
		else
			return o;
	}

    /// <summary>
    /// Returneaza sirul "NULL" in loc de null sau sirul vid.
    /// </summary>
    /// <param name="o">Valoarea de intrare.</param>
    /// <returns>Valoarea de iesire.</returns>
    public static object GetSQLValueNULL(object o, bool asString)
    {
        return GetSQLValueNULL(o, asString, int.MaxValue);
    }
    public static object GetSQLValueNULL(object o, bool asString, int maxLength)
    {
		if ((o == null) || (o is System.DBNull) || ((o is string) && ((string)o == "")))
            return "NULL";
        else
            if (asString)
            {
                string actualValue = o.ToString();
                return "'" + (actualValue.Length > maxLength ? actualValue.Substring(0, maxLength) : actualValue).Replace("'", "''") + "'";
            }
            else
                return o;
    }

	/// <summary>
	/// Returneaza System.DBNull.Value in loc de null sau sirul vid.
	/// </summary>
	/// <param name="o">Valoarea de intrare.</param>
	/// <param name="strType">Tipul obiectului.</param>
	/// <returns>Valoarea de iesire.</returns>
	public static object GetSQLValue(object o, string strType)
	{
		if ((o == null) || (o is System.DBNull) || ((o is string) && ((string)o == "")))
			return System.DBNull.Value;
		else if (strType == "datetime" || strType == "smalldatetime")
			return DateTime.Parse(o.ToString());
		else
			return o;
	}

	/// <summary>
	/// Returneaza System.DBNull.Value in loc de null sau sirul vid.
	/// </summary>
	/// <param name="o">Valoarea de intrare.</param>
	/// <param name="strType">Tipul obiectului.</param>
	/// <param name="strLang">Cultura pentru DateTtime.</param>
	/// <returns>Valoarea de iesire.</returns>
	public static object GetSQLValue(object o, string strType, string strLang)
	{
		if ((o == null) || (o is System.DBNull) || ((o is string) && ((string)o == "")))
			return System.DBNull.Value;
		else if (strType == "datetime" || strType == "smalldatetime")
		{
			IFormatProvider ci = new System.Globalization.CultureInfo(strLang, true);
			return DateTime.Parse(o.ToString(), ci);
		}
		else
			return o;
	}

	/// <summary>
	/// Returneaza un array dintr-o coloana a unui view.
	/// </summary>
	/// <param name="dv">View-ul cu date.</param>
	/// <param name="strColumn">Coloana.</param>
	/// <returns>Array cu valori.</returns>
	public static string[] GetArrayFromColumn(DataView dv, string strColumn)
	{
		string[] s = new string[dv.Count];
		for (int i = 0; i < dv.Count; ++i)
			s[i] = dv[i][strColumn].ToString();
		return s;
	}

	/// <summary>
	/// Gaseste un control in pagina.
	/// </summary>
	/// <param name="namingContainer">NamingContainer-ul parinte.</param>
	/// <param name="controlId">ID-ul control-ului.</param>
	/// <returns>Controlul.</returns>
	public static Control RecursiveFindControl(Control namingContainer, string controlId)
	{
		Control c = namingContainer.FindControl(controlId);

		if (c != null)
			return c;

		if (namingContainer.NamingContainer != null)
			return RecursiveFindControl(namingContainer.NamingContainer, controlId);

		return null;
	}

	/// <summary>
	/// Cauta un string intr-un array de string-uri.
	/// </summary>
	/// <param name="a">Vectorul in care se va efectua cautarea.</param>
	/// <param name="x">Valoarea cautata.</param>
	/// <returns>Pozitia in care a fost gasita valoarea cautata (0-based), sau -1 daca x nu apare in a.</returns>
	public static int ArrayIndexOf(string[] a, string x)
	{
		if (a == null)
			return -1;
		for (int i = 0; i < a.Length; ++i)
			if (a[i] == x)
				return i;
		return -1;
	}

	/// <summary>
	/// Cauta un string intr-o coloana a unei matrice de string-uri.
	/// </summary>
	/// <param name="a">Matricea in care se va efectua cautarea.</param>
	/// <param name="x">Valoarea cautata.</param>
	/// <param name="p">Indicele coloanei pe care se va efectua cautarea.</param>
	/// <returns>Pozitia in care a fost gasita valoarea cautata (0-based), sau -1 daca x nu apare in a[][p].</returns>
	public static int ArrayIndexOfPos(string[][] a, string x, int p)
	{
		if (a == null)
			return -1;
		for (int i = 0; i < a.Length; ++i)
			if (a[i].Length > p && a[i][p] == x)
				return i;
		return -1;
	}

	public static string GetHeaderText(string strColumnName)
	{
		string strHeaderText = Resources.DatabaseStrings.ResourceManager.GetString(strColumnName);
		return strHeaderText ?? strColumnName;
//		return strHeaderText ?? "-#-" + strColumnName + "-#-";
	}

	public static string GetLanguage(HttpRequest Request)
	{
		if (Request.Cookies["Lang"] == null)
		{
			string strLanguage = "";
			if (Request.UserLanguages != null && Request.UserLanguages.Length > 0)
				strLanguage = Request.UserLanguages[0];
			string[] arAcceptedLanguages = new string[] { "ro-RO", "en-US" };
			if (ArrayIndexOf(arAcceptedLanguages, strLanguage) == -1)
				strLanguage = "ro-RO";	// default language
			HttpCookie c = new HttpCookie("Lang", strLanguage);
			Request.Cookies.Add(c);
		}
		return Request.Cookies["Lang"].Value;
	}

	public static string DoPackDataView(DataRowView drv, string[] arColumns, string[] arColumnsReplacement, string strDatePattern, string strCellSep)
	{
		string[] s = new string[arColumns.Length];
		for (int j = 0; j < arColumns.Length; ++j)
			if (arColumnsReplacement != null && arColumns[j] == "")
				s[j] = arColumnsReplacement[j];
			else
			{
				if (strDatePattern != null && strDatePattern != "" && drv.DataView.Table.Columns[arColumns[j]].DataType.Equals(System.Type.GetType("System.DateTime")))
				{
					if (drv[arColumns[j]] == System.DBNull.Value)
						s[j] = "";
					else
						s[j] = Convert.ToDateTime(drv[arColumns[j]]).ToString(strDatePattern);
				}
				else
					s[j] = drv[arColumns[j]].ToString();
			}
		return string.Join(strCellSep, s);
	}

    public static string UnPackCustomMarkup(string databaseContents)
    {
        return databaseContents.Replace("&b", "<br />").Replace("&s", "&nbsp;");
    }
	public static string UnPackCustomMarkupForPdf(string databaseContents)
	{
		return databaseContents.Replace("&b", "\n").Replace("&s", " ");
	}

	public static string RemoveHTML(string html)
	{
		if (html == null || html == "")
			return "";
		else
		{
			string s = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", "");
			s = s.Replace("&nbsp;", " ");
			return s;
		}
	}

	public static string HiddenExceptionDetails(Exception ex)
	{
		return "&nbsp;<!-- " + ex.ToString().Replace("-->", "--~>") + "-->";
	}

	public static string GetDateFormat()
	{
		return GetDateFormat(System.Threading.Thread.CurrentThread.CurrentCulture.Name);
	}

	public static string GetDateFormat(string strLanguage)
	{
		// System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern
		switch (strLanguage)
		{
			case "en-US":
				return "MM/dd/yyyy";
			case "ro-RO":
				return "dd.MM.yyyy";
			case "ISO":
				return "yyyy-MM-dd";
			default:
				return "dd.MM.yyyy";
		}
	}

	public static string GetTimeFormat()
	{
		return "HH:mm:ss";
	}

	/// <summary>
	/// Seteaza valorile default pentru controalele dintr-o anumita regiune.
	/// </summary>
	/// <param name="cc">Controlul care cuprinde regiunea.</param>
	public static void SetControlDefaultValues(Control cc)
	{
		SetControlDefaultValuesRec(cc);
	}

	/// <summary>
	/// Seteaza valorile default pentru controalele dintr-o anumita regiune.
	/// </summary>
	/// <param name="cc">Controlul care cuprinde regiunea.</param>
	private static void SetControlDefaultValuesRec(Control cc)
	{
		foreach (Control c in cc.Controls)
		{
			if (c is CheckBox)
				((CheckBox)c).Checked = false;
			else if (c is TextBox)
				((TextBox)c).Text = "";
			else if (c is DropDownList)
				((DropDownList)c).SelectedValue = "";
			SetControlDefaultValuesRec(c);
		}
	}

	/// <summary>
	/// Citeste valorile pentru controalele dintr-o anumita regiune.
	/// </summary>
	/// <param name="cc">Controlul care cuprinde regiunea.</param>
	/// <returns>Hashtable-ul cu valorile controalelor (new string[] { strValue, strText }).</returns>
	public static Hashtable GetControlValues(Control cc)
	{
		Hashtable ht = new Hashtable();
		GetControlValuesRec(cc, ref ht);
		return ht;
	}

	/// <summary>
	/// Citeste valorile pentru controalele dintr-o anumita regiune.
	/// </summary>
	/// <param name="cc">Controlul care cuprinde regiunea.</param>
	/// <returns>Hashtable-ul cu valorile controalelor (new string[] { strValue, strText }).</returns>
	private static void GetControlValuesRec(Control cc, ref Hashtable ht)
	{
		foreach (Control c in cc.Controls)
		{
			if (c is CheckBox || c is TextBox || c is DropDownList)
			{
				string strName = c.ID;
				string strValue = "";
				string strText = "";

				if (c is CheckBox)
				{
					if (((CheckBox)c).Checked)
					{
						strValue = ((CheckBox)c).Checked.ToString();
						strText = strValue;
					}
				}
				else if (c is TextBox)
				{
					if (((TextBox)c).Text != "")
					{
						strValue = ((TextBox)c).Text;
						if ((c as TextBox).ToolTip.Equals("Show Calendar"))
							strValue = GetDateInEnglishFormat(strValue);
						strText = strValue;
					}
				}
				else if (c is DropDownList)
				{
					if (((DropDownList)c).SelectedValue != "")
					{
						strValue = ((DropDownList)c).SelectedValue;
						strText = ((DropDownList)c).SelectedItem.Text;
					}
				}

				if (strName.StartsWith("chk") || strName.StartsWith("txt") || strName.StartsWith("ddl") || strName.StartsWith("xxx"))
					strName = strName.Substring(3);
				ht[strName] = new string[] { strValue, strText };
			}

			GetControlValuesRec(c, ref ht);
		}
	}

	public static string GetNumberInLocalFormat(string s)
	{
		try
		{
			Decimal n = Decimal.Parse(s, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowLeadingSign, System.Globalization.CultureInfo.CreateSpecificCulture("en-US").NumberFormat);
			s = n.ToString(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat);
		}
		catch (Exception) { }
		return s;
	}

	public static string GetNumberInEnglishFormat(string s)
	{
		try
		{
			Decimal n = Decimal.Parse(s, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowLeadingSign, System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat);
			s = n.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("en-US").NumberFormat);
		}
		catch (Exception) { }
		return s;
	}

    public static string GetNumberWithDigits(object o, int NumberDecimalDigits, string NumberDecimalSeparator, string NumberGroupSeparator)
    {
        NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
        nfi.NumberDecimalDigits = NumberDecimalDigits;
        nfi.NumberDecimalSeparator = NumberDecimalSeparator;
        nfi.NumberGroupSeparator = NumberGroupSeparator;

        return Convert.ToDecimal(o).ToString("N", nfi);
    }

	public static string GetDateInLocalFormat(string s)
	{
		try
		{
			DateTime dt = DateTime.Parse(s, System.Globalization.CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat);
			s = dt.ToString(GetDateFormat(), System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat);
		}
		catch (Exception) { }
		return s;
	}

	public static string GetDateInEnglishFormat(string s)
	{
		try
		{
			DateTime dt = DateTime.Parse(s, System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat);
			s = dt.ToString(GetDateFormat("en-US"), System.Globalization.CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat);
		}
		catch (Exception) { }
		return s;
	}

	public static string GetDateInSql103Format(DateTime dt)
	{
		return dt.ToString("dd/MM/yyyy");
	}

	public static DateTime GetDate(string s)
	{
		DateTime dt = DateTime.Now;
		try
		{
			dt = DateTime.Parse(s, System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat);
		}
		catch (Exception) { }
		return dt;
	}

	private static System.Collections.Generic.List<System.Globalization.CultureInfo> rawOptions = null;
	private static System.Collections.Generic.List<System.Globalization.CultureInfo> CultureOptions
	{
		get
		{
			if (rawOptions == null)
			{
				rawOptions = new System.Collections.Generic.List<System.Globalization.CultureInfo>();
				rawOptions.Add(System.Globalization.CultureInfo.InvariantCulture);
				rawOptions.Add(System.Globalization.CultureInfo.CurrentCulture);
				rawOptions.Add(System.Globalization.CultureInfo.GetCultureInfo("ro-RO"));
				rawOptions.Add(System.Globalization.CultureInfo.GetCultureInfo("en-US"));
				rawOptions.Add(System.Globalization.CultureInfo.GetCultureInfo("en-GB"));
			}
			return rawOptions;
		}
	}
	public static DateTime GetDateTime(string input, string DateFormat)
	{
		DateTime result;
		if (DateTime.TryParse(input, out result))
			if (result.ToString(DateFormat).Equals(input))
				return result;
		foreach (System.Globalization.CultureInfo format in CultureOptions)
			if (DateTime.TryParse(input, format.DateTimeFormat, System.Globalization.DateTimeStyles.None, out result))
				if (result.ToString(DateFormat).Equals(input))
					return result;
		throw new ApplicationException(string.Format("String '{0}' was not recognized as a valid DateTime.", input));
	}

	public static string GetRequiredInYesNoFormat(string s)
	{
		try
		{
			if (s == "True") s = Resources.DatabaseStrings.Required_True;
			else s = Resources.DatabaseStrings.Required_False;
		}
		catch (Exception) { }
		return s;
	}

	public static object oSyncLog = new object();
	public static void ScrieInLog(HttpServerUtility objServer, string Mesaj)
	{
		ScrieInLog(objServer, Mesaj, "");
	}

	public static void ScrieInLog(HttpServerUtility objServer, string Mesaj, string strLogNameSufix)
	{
		lock (oSyncLog)
		{
			try
			{
				if (!System.IO.Directory.Exists(objServer.MapPath("~/Logs/")))
					System.IO.Directory.CreateDirectory(objServer.MapPath("~/Logs/"));

				string strPath = objServer.MapPath("~/Logs/" + GetLogName(strLogNameSufix));
				System.IO.StreamWriter fSW = System.IO.File.AppendText(strPath);
				fSW.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] " + Mesaj);
				fSW.Flush();
				fSW.Close();
			}
			catch (Exception ex)
			{
				HttpContext.Current.Trace.Warn("error", "Cannot write to log file.", ex);
			}
		}
	}

	private static string GetLogName(string strLogNameSufix)
	{
		return GetLogName(DateTime.Now, strLogNameSufix);
	}

	public static string GetLogName(DateTime dt, string strLogNameSufix)
	{
		return "Log-" + dt.ToString("yyyy-MM-dd") + strLogNameSufix + ".txt";
	}

	public static string GetErrorMessage(string strError)
	{
		if (strError.IndexOf("|") != -1)
		{
			string[] s1 = strError.Split(new char[] { '|' });
			if (s1[0].IndexOf("ERR_") == 0)
			{
				string[] s2 = s1[1].Split(new char[] { ',' });
				string s3 = GetHeaderText(s1[0].Trim());
				if (s3 == "???")
					s3 = s1[0];
				strError = string.Format(s3, s2);
			}
		}
		else
		{
			string s = GetHeaderText(strError.Trim());
			if (s != "???")
				strError = s;
		}
		return strError;
	}

	public static void TransferValues(DataView dvSrc, DataView dvDest)
	{
		string[] arStrColumns = new string[dvSrc.Table.Columns.Count];
		for (int i = 0; i < dvSrc.Table.Columns.Count; ++i)
			arStrColumns[i] = dvSrc.Table.Columns[i].ColumnName;

		TransferValues(dvSrc, dvDest, arStrColumns, arStrColumns, new string[arStrColumns.Length]);
	}

	public static void TransferValues(DataView dvSrc, DataView dvDest, string[] arStrColumns)
	{
		TransferValues(dvSrc, dvDest, arStrColumns, arStrColumns, new string[arStrColumns.Length]);
	}

	public static void TransferValues(DataView dvSrc, DataView dvDest, string[] arStrSrcColumns, string[] arStrDestColumns)
	{
		TransferValues(dvSrc, dvDest, arStrSrcColumns, arStrDestColumns, new string[arStrSrcColumns.Length]);
	}

	public static void TransferValues(DataView dvSrc, DataView dvDest, string[] arStrSrcColumns, string[] arStrDestColumns, string[] arStrDefaultValuesColumns)
	{
		TransferValues(dvSrc, dvDest, arStrSrcColumns, arStrDestColumns, arStrDefaultValuesColumns, "");
	}

	public static void TransferValues(DataView dvSrc, DataView dvDest, string[] arStrSrcColumns, string[] arStrDestColumns, string[] arStrDefaultValuesColumns, string strUniqueColumn)
	{
		bool[] bAllowDBNull = new bool[dvDest.Table.Columns.Count];
		bool[] bReadOnly = new bool[dvDest.Table.Columns.Count];
		for (int i = 0; i < dvDest.Table.Columns.Count; ++i)
		{
			bAllowDBNull[i] = dvDest.Table.Columns[i].AllowDBNull;
			bReadOnly[i] = dvDest.Table.Columns[i].ReadOnly;

			dvDest.Table.Columns[i].AllowDBNull = true;
			dvDest.Table.Columns[i].ReadOnly = false;
		}

		DataRowView drvDest = null;
		foreach (DataRowView drvSrc in dvSrc)
		{
			if (strUniqueColumn != "")
			{
				bool bSkip = false;
				foreach (DataRowView drvDest2 in dvDest)
					if (drvDest2[strUniqueColumn].ToString() == drvSrc[strUniqueColumn].ToString())
						bSkip = true;
				if (bSkip)
					continue;
			}
			drvDest = dvDest.AddNew();
			for (int i = 0; i < arStrSrcColumns.Length; ++i)
			{
				if (arStrDefaultValuesColumns[i] == "" || arStrDefaultValuesColumns[i] == null)
					drvDest[arStrDestColumns[i]] = drvSrc[arStrSrcColumns[i]];
				else
					drvDest[arStrDestColumns[i]] = arStrDefaultValuesColumns[i];
			}
		}

		int iLen = dvDest.Count;
		dvDest.AddNew();
		dvDest.Delete(iLen);

		for (int i = 0; i < dvDest.Table.Columns.Count; ++i)
		{
			try
			{
				dvDest.Table.Columns[i].AllowDBNull = bAllowDBNull[i];
				dvDest.Table.Columns[i].ReadOnly = bReadOnly[i];
			}
			catch (Exception) { }
		}
	}

    public static string GetUserName()
    {
        return System.Threading.Thread.CurrentPrincipal.Identity.Name;
    }

	public static string GetUserID(string username, string password)
	{
		try
		{
			string strUserHostName = HttpContext.Current.Request.UserHostName;

			try
			{
				strUserHostName = System.Net.Dns.GetHostEntry(HttpContext.Current.Request.UserHostAddress).HostName;
			}
			catch (Exception) { }

            if ((HttpContext.Current.Request.QueryString["name"] != null && HttpContext.Current.Request.QueryString["name"] != ""))
            {
                userHipoSession = HttpContext.Current.Request["name"].ToString();
				HttpContext.Current.Session["userHipoSession"] = HttpContext.Current.Request["name"].ToString();
			}

			DataSet ds = Hipocrate.DB.DBConnection.GetData("Users_Login_Select",
                new string[] { "UserName", "Passwd", "LastLang", "UserHostAddress", "UserHostName", "UserHipocrate" },
                new object[] { username, Tools.GetSQLValue(password), Tools.GetLanguage(HttpContext.Current.Request), HttpContext.Current.Request.UserHostAddress, strUserHostName, userHipoSession });

			if (ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Rows[0]["ID"] != System.DBNull.Value)
			{
                userHipo = ds.Tables[0].Rows[0]["Name"].ToString();
                StaffID = ds.Tables[0].Rows[0]["StaffID"].ToString();
				HttpContext.Current.Session["userHipoSession"] = ds.Tables[0].Rows[0]["UserHypo"].ToString();
                userLogin = ds.Tables[0].Rows[0]["UserHypo"].ToString();
				if (!System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
					Tools.ScrieInLog(HttpContext.Current.Server, string.Format("Login (GetUserID)  [SessionID='" + HttpContext.Current.Session.SessionID + "']: Utilizatorul '{0}' s-a logat.", username), Tools.LOG_INFO);
				else
					Tools.ScrieInLog(HttpContext.Current.Server, string.Format("Login (GetUserID)  [SessionID='" + HttpContext.Current.Session.SessionID + "']: Utilizatorul '{0}' s-a re-logat.", username), Tools.LOG_INFO);
				return ds.Tables[0].Rows[0]["ID"].ToString();
			}
			else
			{
				Tools.ScrieInLog(HttpContext.Current.Server, string.Format("Login (GetUserID)  [SessionID='" + HttpContext.Current.Session.SessionID + "']: Utilizatorul '{0}' nu s-a logat.", username), Tools.LOG_INFO);
			}
		}
		catch (Exception)
		{
			throw;
		}
		return "";
	}

	public static DataType GetDataType(string dataType)
	{
		DataType DTTemp = null;

		switch (dataType)
		{
            case ("System.Decimal"):
                DTTemp = DataType.Decimal(2, 18);
                break;
            case ("System.Double"):
                DTTemp = DataType.Float;
                break;
            case ("System.String"):
                DTTemp = DataType.NVarChar(4000);
                break;
            case ("System.Int32"):
                DTTemp = DataType.Int;
                break;
            case ("System.Int64"):
                DTTemp = DataType.BigInt;
                break;
            case ("System.Boolean"):
                DTTemp = DataType.Bit;
                break;
            case ("System.DateTime"):
                DTTemp = DataType.DateTime;
                break;
            case ("System.Char"):
                DTTemp = DataType.Char(1);
                break;
            default:
                DTTemp = DataType.VarChar(50);
                break;
		}
		return DTTemp;
	}

    public static void AddLinkedStyleSheet(Page page, string stylesheet)
    {
        bool bAdded = false;
        foreach (Control c in page.Header.Controls)
            if (c is HtmlLink && ((HtmlLink)c).Href == stylesheet)
            {
                bAdded = true;
                continue;
            }
        if (!bAdded)
        {
            HtmlLink link = new HtmlLink();
            link.Href = stylesheet;
            link.Attributes["rel"] = "stylesheet";
            link.Attributes["type"] = "text/css";

            page.Header.Controls.Add(link);
        }
    }

	public static DataSet AddEmptyRow(DataSet source, params object[] extraData)
	{
		DataRow row = source.Tables[0].NewRow();
		for (int i = 0; i < extraData.Length; i += 2)
			row[extraData[i].ToString()] = extraData[i + 1];
		source.Tables[0].Rows.InsertAt(row, 0);
		return source;
	}

	public static void DataBindDDL(DropDownList control, DataSet ds, string valueField, string textField)
	{
		control.DataValueField = valueField;
		control.DataTextField = textField;
		control.DataSource = ds;
		control.DataBind();
	}

	public static string prefixFill(string input, char prefix, int requiredLength)
	{
		if (input.Length < requiredLength)
			return new string(prefix, requiredLength - input.Length) + input;
		else
			return input;
	}

    public static object GetDate(TextBox txtControl)
    {
        string value = txtControl.Text.Trim();
        if (value.Length == 0)
            return null;
        DateTime result;
        if (DateTime.TryParse(value, out result))
            return result.ToShortDateString();
        return null;
    }

    public static string getSQLFormat_120(DateTime dt)
    {
		return dt.ToString("yyyy-MM-dd HH:mm:ss");
    }

    public static string getSQLFormat_103(DateTime dt)
    {
		return dt.ToString("dd/MM/yyyy");
    }

    public static string getSQLFormat_103E(DateTime dt)
    {
		return dt.ToString("dd/MM/yyyy HH:mm:ss");
    }

    public static string getSQLFormat_ISO(object dt)
    {
        if (dt is DateTime)
            return "'" + ((DateTime)dt).ToString("yyyy-MM-dd HH:mm:ss") + "'";
        else if (dt is DBNull)
            return "NULL";
        throw new ApplicationException(dt.ToString() + " -- " + dt.GetType().ToString());
    }

    public static DateTime getDateFormat_CultureInfo(string date)
    {
        System.Globalization.CultureInfo en = new System.Globalization.CultureInfo("en-GB");
        return Convert.ToDateTime(date, en);
    }

    public static DateTime getDateFormat_CultureInfo_RO(string date)
    {
        System.Globalization.CultureInfo en = new System.Globalization.CultureInfo("ro-RO");
        return Convert.ToDateTime(date, en);
    }

    public static bool parseNumber(string nrToCheck)
    {
        foreach (char s in nrToCheck)
        {
            if (s.ToString() != "0" || s.ToString() != "1" || s.ToString() != "2" || s.ToString() != "3" || s.ToString() != "4" ||
                s.ToString() != "5" || s.ToString() != "6" || s.ToString() != "7" || s.ToString() != "8" || s.ToString() != "9" || s.ToString() != ".")
            {
                return false;
            }
            else
                return true;
        }
        return true;
    }

    public static object GetDateFormatDBF(object dateString)
    {
        if (dateString != DBNull.Value)
            return "{^" + dateString + "}";
        else
            return "{}";
    }

    public static object getDBFFormat_ISO(object dt)
    {
        if (dt is DateTime)
            return ((DateTime)dt).ToString("yyyy-MM-dd HH:mm:ss");
        else if (dt is DBNull)
            return DBNull.Value;
        throw new ApplicationException(dt.ToString() + " -- " + dt.GetType().ToString());
    }
}
